import random

import requests

from api import log
from api.api_recharge import ApiRecharge
from api.api_register_login import ApiRegisterLogin
from tools import common_assert, html_parser


class TestRecharge:
    # 初始化
    def setup_method(self):
        # 1、获取session对象
        log.info("获取session对象")
        self.session = requests.session()
        # 2、获取ApiRecharge对象
        log.info("获取ApiRecharge对象")
        self.api = ApiRecharge(self.session)
        # 获取ApiRegisterLogin对象
        log.info("获取ApiRegisterLogin对象")
        self.login = ApiRegisterLogin(self.session)

    # 结束
    def teardown_method(self):
        # 关闭session对象
        log.info("关闭sessino对象")
        self.session.close()

    # 1、图片验证码接口 测试
    def test01_img_code(self,random=123123):
        try:
            # 调用图片url
            result = self.api.url_img_code(random)
            log.info("图片验证码接口测试结果为:{}".format(result.status_code))
            # 断言
            common_assert(result, status_code=result.status_code)
            log.info("图片验证码断言成功")
        except Exception as e:
            log.error(e)
            raise

    # 2、充值 测试
    def test02_recharge(self, amount=10000, valicode=8888, expect_json="form", expect_text="OK"):
        try:
            # 1、登录
            self.login.api_login()
            # 2、获取图片验证码
            self.api.url_img_code(123123)
            # 3、后台请求充值
            result = self.api.url_recharge(amount=amount, valicode=valicode)
            log.info("充值接口测试结果为:{}".format(result.json()))
            # 断言
            common_assert(result, expect_json=expect_json)
            log.info("充值接口断言通过")
            # 4、三方充值
            data = html_parser(result)
            result2 = self.session.post(url=data[0], data=data[1])
            log.info("三方充值接口测试结果为:{}".format(result2.text))
            # 三方充值 断言
            common_assert(result2, expect_text=expect_text)
        except Exception as e:
            log.error(e)
            raise
